<?php

/**
 * @package Blog_Filter
 * @version 0.1
 */
 
/**
 * Plugin Name: Blog Filter
 * Description: Filter by category/author.
 * Version: 0.1
 * Author: Johan Sall Larsson
 * Author URI: http://www.johansalllarsson.se
 */

/**
 * Usage: 
 * For pre defines filters use the 'filter' attribute i.e. [blog_filter filter_name="start"]
 * or set the attributes yourself e.g. [blog_filter cat="1,2"] 
 */
	
	/**
	 * Database filter format
	 */
	define('FILTER_FORMAT', 'blog-filter-%s-html');
	
	/**
	 * Filter name
	 */
	 define('FILTER_NAME', 'filter_name');
	
	include_once( WP_PLUGIN_DIR . "/blog-filter/options.php" );

	// load_plugin_textdomain( 'blog-filter', false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' );
	
	function blog_filter_func($args) {
		
		$atts =	shortcode_atts (
			array (
				FILTER_NAME  		=> '',
				'author'	  		=> '',
				'cat'		  		=> '',
				'orderby'     		=> 'post_date',
				'order'       		=> 'DESC',
				'posts_per_page' 	=> 5,
				'nopaging'			=> false,
				'include'			=> '',
				'exclude'			=> '',
				'tpl'				=> false,
				'paged'				=> ''
			), $args
		);
		
		if ( !empty($atts[FILTER_NAME]) ) {
			$atts =  shortcode_atts( $atts, blog_filter_build_filter_settings($atts[FILTER_NAME]) );
			// override filter specifics if attributes are set in the shortcode.
			if ( !empty($args['posts_per_page']) )
				$atts['posts_per_page'] = $args['posts_per_page'];
			if ( !empty($args['nopaging']) )
				$atts['nopaging'] = $args['nopaging'];
			if ( !empty($args['orderby']) )
				$atts['orderby'] = $args['orderby'];
			if ( !empty($args['order']) )
				$atts['order'] = $args['order'];
		}
		
		if ( $atts['tpl'] ) {
			// Runs by widget code, outside the loop
			$tpl_path = WP_PLUGIN_DIR . sprintf("/blog-filter/%s.tpl", $atts[FILTER_NAME]);
			if ( file_exists($tpl_path) ) {
				$tpl = file_get_contents($tpl_path);
				if ( !empty($tpl) ) {
					blog_filter_non_loop_query($atts, $tpl);
				}
			}
		} else {
			// Runs within the loop
			blog_filter_query($atts);
		}
		
	}
	
	/**
	 * Query the database (loop)
	 * @params $args
	*/
	function blog_filter_query($args) {
		global $wp_query;
		$wp_query = new WP_Query($args);
		$wp_query->query($args);
		wp_reset_postdata();
	}
	
	/**
	 * Query the database and parse template
	 * @params $args
	 * @params $tpl
	*/
	function blog_filter_non_loop_query($args, $tpl) {
		if ( !empty($tpl) ) {
			$wp_query = new WP_Query();
			$result = $wp_query->query($args);
			$date_format = get_option('date_format');
			$time_format = get_option('time_format');
			foreach ($result as $post) {
				blog_filter_parse_template($post, $tpl, $date_format, $time_format);
			}
		}
	}
	
	/**
	 * Parse the template
	 * @param $post
	 * @param $tpl
	 * @param $date_format
	 * @param $time_format
	*/
	function blog_filter_parse_template($post, $tpl, $date_format, $time_format) {
		$tpl = str_replace("%post_id%", $post->ID, $tpl);
		$tpl = str_replace("%post_title%", $post->post_title, $tpl);
		$tpl = str_replace("%post_date%", date_i18n($date_format, strtotime($post->post_date)), $tpl);
		$tpl = str_replace("%post_time%", date_i18n($time_format, strtotime($post->post_date)), $tpl);
		if ( strpos($tpl, "%post_thumbnail%") !== false ) {
			if ( has_post_thumbnail($post->ID) ) {
				$tpl = str_replace("%post_thumbnail%", get_the_post_thumbnail($post->ID,thumbnail), $tpl);
			} else {
				$tpl = str_replace("%post_thumbnail%", get_avatar($post->post_author, 170), $tpl);
			}
		}
		$user = get_userdata($post->post_author);
		$tpl = str_replace("%post_author_link%", site_url() . "/author/" . $user->user_nicename . "/", $tpl);
		$tpl = str_replace("%post_author%", $user->display_name, $tpl);
		$tpl = str_replace("%post_author_avatar%", get_avatar($post->post_author, 48), $tpl);
		$tpl = str_replace("%post_content%", wpautop(wptexturize($post->post_content)), $tpl);
		$tpl = str_replace("%post_excerpt%", blog_filter_excerpt($post->post_content, $post->post_excerpt), $tpl);
		$tpl = str_replace("%post_permalink%", get_permalink($post), $tpl);
		$tpl = str_replace("%post_group%", get_cimyFieldValue($post->post_author,'GRUPP'), $tpl);
		echo $tpl;
	}
	
	/**
	 * Sets the filter settings
	 * @param $filter_name
	 */
	function blog_filter_build_filter_settings($filter_name) {
		$filters = get_option('blog_filter_settings');
		$filter = $filters[$filter_name];
		if ( $filter != null && is_array($filter) ) {
			$args = array(
				FILTER_NAME 		=> $filter_name,
				'author' 			=> ( !empty($filter['u']) && count($filter['u']) > 0 ) ? implode (',', $filter['u']) : '',
				'cat' 				=> ( !empty($filter['c']) && count($filter['c']) > 0 ) ? implode (',', $filter['c']) : '',
				'posts_per_page' 	=> ( is_numeric($filter['p']) && !empty($filter['p']) ) ? (int)$filter['p'] : 5,
				'nopaging' 			=> $filter['e'] != 1 ? true : false,
				'paged' 			=> get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1
			);
			return $args;
		}
		return array();
	}
	
	/**
	 * Extracts an excerpt
	 * @param $text
	 * @param $excerpt
	 */
	function blog_filter_excerpt($text, $excerpt) {
		if ($excerpt) { 
			return $excerpt;
		}
		$text = strip_shortcodes( $text );
		$text = apply_filters('the_content', $text);
		$text = str_replace(']]>', ']]&gt;', $text);
		$text = strip_tags($text);
		$excerpt_length = apply_filters('excerpt_length', 55);
		$excerpt_more = apply_filters('excerpt_more', ' ' . '[...]');
		$words = preg_split("/[\n\r\t ]+/", $text, $excerpt_length + 1, PREG_SPLIT_NO_EMPTY);
		if ( count($words) > $excerpt_length ) {
			array_pop($words);
			$text = implode(' ', $words);
			$text = $text . '...';
		} else {
			$text = implode(' ', $words);
		}
		return apply_filters('wp_trim_excerpt', $text, $raw_excerpt);
	}
	
	/**
	 * Deactivation function for plugin
	 */
	function blog_filter_deactivate() {
		delete_option('blog_filter_settings');
	}
	
	add_shortcode('blog_filter', 'blog_filter_func');
	register_deactivation_hook(__FILE__, 'blog_filter_deactivate');
	
?>